<template>
  <div>
    <div class="dict-header">
      <a-form
          layout="inline"
          :model="searchState"
          @finish="searchFinish"
      >
        <a-form-item v-bind="validateInfos.name" label="字典名">
          <a-input v-model:value="searchState.name" placeholder="请输入查询的名称"/>
        </a-form-item>
        <a-form-item v-bind="validateInfos.type_id" label="分类">
          <a-select v-model:value="searchState.type_id" placeholder="请选择需要查询的分类" style="width: 120px">
            <a-select-option :value="item.id" v-for="item in categoryState">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button
              type="primary"
              html-type="submit"
              style="margin-right: 10px"
          >
            查询
          </a-button>
          <a-button
              style="margin-right: 10px"
              type="primary"
              @click="resetFields"
          >
            重置
          </a-button>
          <a-button
              type="primary"
              @click="createClick"
          >
            新建
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-table :dataSource="dataSource" :columns="columns" bordered :pagination="pagination">
      <template #bodyCell="{column,record}">
        <template v-if="column.key === 'action'">
          <a-button type="primary" style="margin-right: 10px" @click="editClick(record)">编辑</a-button>
          <a-popconfirm
              :title="'是否确定删除'+record.name+'分类吗?'"
              ok-text="确定"
              cancel-text="取消"
              @confirm="delClick(record.id)"
          >
            <a-button type="primary" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
  <a-modal v-model:visible="modalState.visible" :title="modalState.title" :footer="null"
           @cancel="()=>{dictResetFields();modalState.visible = false}">
    <a-form
        :model="dicState"
        @finish="dictFinish">
      <a-form-item v-bind="dictValidateInfos.name" label="字典名称">
        <a-input v-model:value="dicState.name" placeholder="请输入字典的名称"/>
      </a-form-item>

      <a-form-item v-bind="dictValidateInfos.type_id" label="字典分类">
        <a-select v-model:value="dicState.type_id" placeholder="请选择需要查询的分类" style="width: 120px">
          <a-select-option :value="item.id" v-for="item in categoryState">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 7 }">
        <a-button
            type="primary"
            html-type="submit"
            style="margin-right: 10px"
        >
          提交
        </a-button>
        <a-button
            style="margin-right: 10px"
            type="primary"
            @click="dictResetFields"
        >
          重置
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">

import {onMounted, reactive, ref, toRaw, watchEffect} from "vue";
import {useForm} from "ant-design-vue/es/form";
import type {DictCategoryType, DictType, MetaType, ModalType, PageAdnSizeType} from "@/util/publicType";
import {addDict, delDict, dictList, editDict} from "@/api/api";
import {AxiosResponse} from "axios";
import {message} from "ant-design-vue";
import moment from "moment";
import {useDictCategory} from "@/Hooks";

// 搜索type
interface SearState {
  name: string,
  type_id: string
}

// 表data类型
interface DataType {
  id: string,
  type_id: string,
  created_at: number | string,
  name: string,
  categoryName: string,
  fieldCategory: {
    id: string,
    name: string
  }
}

// 表数据
const dataSource = ref<DataType[]>([]);

// 当前页和条数
const pageAndSize = reactive<PageAdnSizeType>({
  page: 1,
  size: 15,
});

// 当前数据
const currentData = ref<DataType | null>(null)

// 搜索參數
const query = reactive<{ typeId: string | null, name: string | null }>({
  typeId: null,
  name: null
});

// 控制弹窗
const modalState = reactive<ModalType>({
  visible: false,
  title: "新建字典"
})

const {categoryState} = useDictCategory();

// 分页
const pagination = reactive({
  total: 0,
  current: pageAndSize.page,
  // 默认每页显示条数
  defaultPageSize: pageAndSize.page,
  // 每页条数
  pageSize: pageAndSize.size,
  // 是否快速跳转
  showQuickJumper: true,
  // 是否可以改变pagesize
  showSizeChanger: true,
  // 总条数
  showTotal: (total: number) => "总条数：" + total,
  //页码改变或者条数的回调
  onChange: (p: number, ps: number) => {
    pageAndSize.page = p;
    pageAndSize.size = ps;
  },
});

// 表头
const columns = [
  {
    title: "字典名称",
    dataIndex: "name",
    key: 'name',
    align: "center",
  },
  {
    title: "字典分类",
    dataIndex: "categoryName",
    key: 'categoryName',
    align: "center",
  },
  {
    title: "生成时间",
    dataIndex: "created_at",
    key: 'created_at',
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: 'action',
    align: "center",
  }
]

// 筛选表单状态
const searchState = reactive<SearState>({
  name: "",
  type_id: ""
});

// 字典表单状态
let dicState = reactive<DictType>({
  type_id: "",
  name: ""
});

// 筛选表单校验
const searchRuleRef = reactive({
  name: [
    {
      required: false,
    }
  ],
  type_id: [
    {
      required: false
    }
  ]
});
// 字典表单校验
const dictRuleRef = reactive({
  name: [
    {
      required: true,
      message: "请输入字典名称"
    }
  ],
  type_id: [
    {
      required: true,
      message: "选择字典类型"
    }
  ]
})


// 筛选表单事件获取
const {resetFields, validate, validateInfos} = useForm(searchState, searchRuleRef);
// 字典表单事件获取
const dictResetFields = useForm(dicState, dictRuleRef).resetFields;
const dictValidate = useForm(dicState, dictRuleRef).validate;
const dictValidateInfos = useForm(dicState, dictRuleRef).validateInfos;

//搜索触发
const searchFinish = () => {
  validate().then(() => {
    const {name, type_id} = toRaw(searchState);
    if (!name) {
      query.name = null;
    } else {
      query.name = name;
    }
    if (!type_id) {
      query.typeId = null
    } else {
      query.typeId = type_id
    }
  })
}

// 字典触发
const dictFinish = () => {
  dictValidate().then(() => {
    let request: Promise<AxiosResponse>;
    console.log(currentData)
    if (currentData.value) {
      request = editDict(currentData?.value?.id as string, toRaw(dicState));
    } else {
      request = addDict(toRaw(dicState));
    }
    request.then(() => {
      dictResetFields();
      getData(pageAndSize.page, query.typeId, query.name);
      message.success("操作成功");
      modalState.visible = false;
    }, err => message.error(err))
  })
}

// 请求
const getData = (page: number, typeId: string | null = null, name: string | null = null) => {
  dictList(page, pageAndSize.size, typeId, name).then((r: AxiosResponse) => {
    let data: DataType[] = r.data.data.data;
    const meta: MetaType = r.data.data.meta;
    pagination.pageSize = meta.perSize;
    pagination.total = meta.total;
    pagination.current = meta.currentPage;
    data = data.map(v => {
      return {
        ...v,
        categoryName: v.fieldCategory.name,
        created_at: moment((v.created_at as number) * 1000).format("YYYY-MM-DD HH:mm:ss")
      }
    });
    dataSource.value = data;
  }, err => message.error(err));
}

watchEffect(() => {
  dataSource.value = []
  getData(pageAndSize.page, query.typeId, query.name)
})

// 删除分类
const delClick = (id: string) => {
  delDict(id).then(() => {
    message.success("删除成功");
    getData(pageAndSize.page, query.typeId, query.name);
  }, err => message.error(err))
}

// 編輯分类
const editClick = (v: DataType) => {
  modalState.title = "编辑字典";
  modalState.visible = true;
  currentData.value = v;
  dicState = Object.assign(dicState, v);
}

// 新建
const createClick = () => {
  currentData.value = null;
  modalState.visible = true;
  modalState.title = "新建字典";
}
</script>

<style scoped lang="less">
.dict-header {
  padding: 30px 0;
}
</style>